//
//  BDMinmaoHomeViewController.m
//  BeidouMall
//
//  Created by qie on 16/7/6.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDMinmaoHomeViewController.h"
#import "SDCycleScrollView.h"
#import "BDGoodDetailViewController.h"
#import "BDGanziHomeHeaderView.h"
#import "BDGanziTypeViewController.h"
#import "BDGanziSearchViewController.h"

#define firstHeightWidthRatio 1.8
#define typeHeightWidthRatio 0.8 // 300 : 375
#define hotHeightWidthRatio 1// 1 : 1
#define kPageSize 6

@interface BDMinmaoHomeViewController ()  < UITableViewDelegate,
                                            UITableViewDataSource,
                                            UICollectionViewDelegate,
                                            UICollectionViewDataSource,
                                            SDCycleScrollViewDelegate,
                                            BDGanziHomeHeaderViewDelegate,
                                            SimplePopupViewDelegate >

{
    NSInteger _curPage;
    NSArray *_firstList;// banner列表
    NSMutableArray *_secondList;// hot列表
    
    CGFloat _recomHeightWidthRatio;// 推荐商品cell高宽比例
    NSUInteger _selectControllerIndex;// tabbar选中index
    
    BDGanziHomeHeaderView *_ganziHeaderView;
    UIImageView *_navBarHairlineImageView;// 原生导航栏上的黑线
    SimplePopupView *_popView;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *topTextField;

@end

@implementation BDMinmaoHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 处理tableView上面多出来20个像素(是因为自动布局的缘故)
    self.edgesForExtendedLayout = UIRectEdgeNone;
    // 自定义tableview刷新的头部和尾部
    [self setTableViewHeader];
    [self setTableViewFooter];
    _secondList = [[NSMutableArray alloc] init];
    [_tableView.mj_header beginRefreshing];
    _curPage = 0;
    
    _topTextField.layer.cornerRadius = 5.0;
    _topTextField.layer.masksToBounds = YES;
    
    [self setHeaderPopView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self hideNavgationBarBlackLine];
    // nav_bg2一个透明的图片替换原来的nav_bg
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg2"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent = YES;
    _ganziHeaderView = [[NSBundle mainBundle] loadNibNamed:@"BDGanziHomeHeader" owner:nil options:nil].firstObject;
    _ganziHeaderView.frame = CGRectMake(0.0, 0.0, kScreen_Width, 64.0);
    _ganziHeaderView.tag = 941;
    _ganziHeaderView.delegate = self;
    _ganziHeaderView.titleImageView.image = [UIImage imageNamed:@"minmaojingpin"];
    _ganziHeaderView.typeTitleLabel.text = NSLocalizedString(@"type", nil);
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        _ganziHeaderView.typeTitleLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
    }
    [self.navigationController.view addSubview:_ganziHeaderView];
    //  为导航栏添加阴影
    [self dropShadowWithOffset:CGSizeMake(0, 0)
                        radius:2
                         color:[UIColor lightGrayColor]
                       opacity:0.8];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _navBarHairlineImageView.hidden = NO;
    
    if (_ganziHeaderView) {
        [_ganziHeaderView removeFromSuperview];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private method

- (void)reloadData:(id) sender {
    _curPage = 1;
    // 民贸BANNER
    NSString *url1 = [NSString stringWithFormat:@"%@%@?currentPage=%d&pageSize=%d&storeType=%@&hotType=%@",
                      [BDNetworking shareInstance].baseUrl,
                      Good_Query,
                      1,
                      20,
                      @"MINMAO_CHAIN",
                      @"STORE_BANNER"];
    [[BDNetworking shareInstance] postWithUrl:url1 sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([_tableView.mj_header isRefreshing]) {
                [_tableView.mj_header endRefreshing];
            }
        });
        if (error) {
            NSLog(@"获取民贸BANNER失败 %@",error);
        } else {
            NSLog(@"BANNER results = %@",results);
            NSDictionary *resultDic = (NSDictionary *)results;
            _firstList = resultDic[@"objects"];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
                [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            });
        }
    }];
    // 甘孜HOT
    if ([_tableView.mj_footer isRefreshing]) {
        
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{// 恢复为普通状态
            [_tableView.mj_footer resetNoMoreData];
        });
        
        NSString *url3 = [NSString stringWithFormat:@"%@%@?currentPage=%d&pageSize=%d&storeType=%@&hotType=%@",
                          [BDNetworking shareInstance].baseUrl,
                          Good_Query,
                          1,
                          kPageSize,
                          @"MINMAO_CHAIN",
                          @"STORE_HOT"];
        [[BDNetworking shareInstance] postWithUrl:url3 sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _tableView.mj_footer.hidden = NO;
                if ([_tableView.mj_header isRefreshing]) {
                    [_tableView.mj_header endRefreshing];
                }
            });
            if (error) {
                NSLog(@"获取民贸HOT失败 %@",error);
            } else {
                NSLog(@"HOT results = %@",results);
                NSDictionary *resultDic = (NSDictionary *)results;
                NSArray *resultList = resultDic[@"objects"];
                [_secondList removeAllObjects];
                [_secondList addObjectsFromArray:resultList];
                if (_secondList.count > 0) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
                        [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                    });
                }
            }
        }];
    }
}

- (void)reloadDataByFooter:(id) sender {
    if ([_tableView.mj_header isRefreshing]) {
        
    } else {
        _curPage = _curPage + 1;
        // 甘孜HOT
        NSString *url3 = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&storeType=%@&hotType=%@",
                          [BDNetworking shareInstance].baseUrl,
                          Good_Query,
                          (long)_curPage,
                          kPageSize,
                          @"MINMAO_CHAIN",
                          @"STORE_HOT"];
        [[BDNetworking shareInstance] postWithUrl:url3 sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([_tableView.mj_footer isRefreshing]) {
                    [_tableView.mj_footer endRefreshing];
                }
            });
            if (error) {
                NSLog(@"获取民贸HOT失败 %@",error);
            } else {
                NSLog(@"民贸HOT results = %@",results);
                NSDictionary *resultDic = (NSDictionary *)results;
                NSArray *resultList = resultDic[@"objects"];
                if ([resultList count] > 0) {
                    if ([resultList count] < kPageSize) {// 数据不够分页,显示没有更多了
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    }
                    [_secondList addObjectsFromArray:resultList];
                } else {
                    if (_curPage > 1) { // 分页引起的刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    }
                }
                if (_secondList.count > 0) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
                        [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                    });
                }
            }
        }];
    }
}

- (void)setTableViewHeader {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData:nil];
    }];
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        header.stateLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
    }
    
    [header setTitle:NSLocalizedString(@"Pull down to refresh", nil) forState:MJRefreshStateIdle];
    [header setTitle:NSLocalizedString(@"Release to refresh", nil) forState:MJRefreshStatePulling];
    [header setTitle:NSLocalizedString(@"Loading ...", nil) forState:MJRefreshStateRefreshing];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    _tableView.mj_header = header;
}

- (void)setTableViewFooter {
    _tableView.mj_footer = [MJDIYBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadDataByFooter:)];
}

- (void)hideNavgationBarBlackLine {
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                NSArray *list2 = imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
                        _navBarHairlineImageView = imageView2;
                        _navBarHairlineImageView.hidden = YES;
                    }
                }
            }
        }
    }
}

- (void)setHeaderPopView {
    NSArray *tmpArray = @[NSLocalizedString(@"home", nil),NSLocalizedString(@"message", nil)];
    NSArray *images = @[@"homeback",@"messageback"];
    //左
    _popView = [[SimplePopupView alloc] initWithFrame:CGRectMake(kScreen_Width - 130.0, 55.0, 120.0, 80.0)
                                         andDirection:PopViewDirectionTop
                                            andTitles:tmpArray
                                            andImages:images
                                       trianglePecent:0.5]; //箭头位于popview中间0.5位置
    [self.navigationController.navigationBar showPopView:_popView AtPoint:CGPointMake(0.5, 0)];//箭头位于button的x=0.y=0.5比例处
    _popView.delegate = self; //需要正式使用时注意代理
}

- (void)dropShadowWithOffset:(CGSize)offset
                      radius:(CGFloat)radius
                       color:(UIColor *)color
                     opacity:(CGFloat)opacity {// 导航栏下边阴影
    
    // Creating shadow path for better performance
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, self.navigationController.navigationBar.bounds);
    self.navigationController.navigationBar.layer.shadowPath = path;
    CGPathCloseSubpath(path);
    CGPathRelease(path);
    
    self.navigationController.navigationBar.layer.shadowColor = color.CGColor;
    self.navigationController.navigationBar.layer.shadowOffset = offset;
    self.navigationController.navigationBar.layer.shadowRadius = radius;
    self.navigationController.navigationBar.layer.shadowOpacity = opacity;
    
    // Default clipsToBounds is YES, will clip off the shadow, so we disable it.
    self.navigationController.navigationBar.clipsToBounds = NO;
    
}

#pragma mark BDGanziHomeHeaderViewDelegate

- (void)backMethod {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)homeMethod:(UIButton *)sender {
    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"ThirdStoryboard" bundle:[NSBundle mainBundle]];
    BDGanziTypeViewController *vc = [stroyboard instantiateViewControllerWithIdentifier:@"ganziTypeStoryboardID"];
    NSArray *firstArr = @[@"食品",@"服饰",@"药材",@"奢侈礼品",@"手工艺",@"其他"];
    NSArray *secondArr = @[@[@"菌类",@"肉类",@"保健品",@"冷冻生鲜",@"干货",@"特色饮品",@"其他"],
                           @[@"包类",@"鞋服",@"首饰",@"配件",@"户外",@"生活",@"其他"],
                           @[@"药材"],
                           @[@"非物质文化遗产",@"其他"],
                           @[@"手工艺"],
                           @[@"图书",@"生鲜",@"干货",@"其他"]];
    
    
    vc.firstArr = firstArr;
    vc.secondArr = secondArr;
    vc.storeType = @"MINMAO_CHAIN";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)simplePopupView:(SimplePopupView *)popView clickAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"代理方法，点击了第%ld行",(long)indexPath.row);
    if (indexPath.row == 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    } else if (indexPath.row == 1) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Still in process", nil)];
    }
}

#pragma mark tableView dataSrouce

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        static NSString *cellStr = @"homePageCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        if ([cell viewWithTag:101] && _firstList.count > 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                SDCycleScrollView *cycleScrollView = (SDCycleScrollView *)[cell viewWithTag:101];
                NSMutableArray *imagesURLStrings = [NSMutableArray array];
                for (NSDictionary *goodDic in _firstList) {
                    NSString *icon = goodDic[@"icon"];
                    if (![icon isEqual:[NSNull null]] &&
                        icon != nil) {
                        [imagesURLStrings addObject:icon];
                    }
                }
                cycleScrollView.imageURLStringsGroup = imagesURLStrings;
                cycleScrollView.autoScrollTimeInterval = 3.0;
            });
            
        } else if (cell.contentView.subviews.count == 1 && _firstList.count > 0) {// 第一次加载
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableArray *imagesURLStrings = [NSMutableArray array];
                for (NSDictionary *goodDic in _firstList) {
                    NSString *icon = goodDic[@"icon"];
                    if (![icon isEqual:[NSNull null]] &&
                        icon != nil) {
                        [imagesURLStrings addObject:icon];
                    }
                }
                SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Width / 1.8) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
                cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
                cycleScrollView.currentPageDotColor = RGBColor(195, 3, 3); // 自定义分页控件小圆标颜色
                cycleScrollView.pageDotColor = RGBColor(210, 210, 210);
                cycleScrollView.imageURLStringsGroup = imagesURLStrings;
                cycleScrollView.tag = 101;
                [cell addSubview:cycleScrollView];
            });
        }
        
        return cell;
    } else if (indexPath.row == 1) {
        static NSString *cellStr = @"homeHotCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        
        UIView *headerView = [cell viewWithTag:801];
        UIView *line1 = [headerView viewWithTag:101];
        for (NSLayoutConstraint* constraint in line1.constraints) {
            if (constraint.firstAttribute == NSLayoutAttributeHeight) {
                constraint.constant = 0.5;
            }
        }
        line1.height = 0.5;
        UIView *line2 = [headerView viewWithTag:102];
        for (NSLayoutConstraint* constraint in line2.constraints) {
            if (constraint.firstAttribute == NSLayoutAttributeHeight) {
                constraint.constant = 0.5;
            }
        }
        line2.height = 0.5;
        
        UICollectionView *collectionView = (UICollectionView *)[cell viewWithTag:901];
        [collectionView reloadData];
        
        return cell;
    } else {
        static NSString *cellStr = @"homeRecomCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        
        UICollectionView *collectionView = (UICollectionView *)[cell viewWithTag:902];
        [collectionView reloadData];
        
        return cell;
    }
}

#pragma mark tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width,height;
    if (indexPath.row == 0) {
        return kScreen_Width / firstHeightWidthRatio;
    } else if (indexPath.row == 1) {
        width = [UIScreen mainScreen].bounds.size.width;
        height = width * typeHeightWidthRatio;
        return height + 35.0;
    }  else if (indexPath.row == 2) {
        width = ([UIScreen mainScreen].bounds.size.width - 12.0 - 8.0) / 2;
        if (kScreen_Width <= 320.0) {
            _recomHeightWidthRatio = 1.4675;
        } else if (kScreen_Width > 320.0 && kScreen_Width <= 375.0) {
            _recomHeightWidthRatio = 1.4675;
        } else {
            _recomHeightWidthRatio = 1.4675;
        }
        height = width * _recomHeightWidthRatio;
        if (_secondList.count > 0) {
            NSInteger count = 0;
            if (_secondList.count % 2 != 0) {
                count = 1;
            }
            count = count + _secondList.count / 2;
            return height * count + 30.0;
        } else {
            return 0;
        }
        return height + 40.0 + 87.0;// 30.0 推荐商品标签高度
    }
    return 0.0;
}

#pragma mark - UITextField delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"ThirdStoryboard" bundle:[NSBundle mainBundle]];
    BDGanziSearchViewController *searchVC = [stroyboard instantiateViewControllerWithIdentifier:@"ganziSearchStoryboardID"];
    searchVC.searchType = YES;
    searchVC.storeType = @"MINMAO_CHAIN";
    [self.navigationController pushViewController:searchVC animated:YES];
    
    return NO;// 是否循序文本字段开始编辑
}

#pragma mark - UIScrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        
    }
}

#pragma mark - colletionView delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView.tag == 901) {
        return 3;
    } else if (collectionView.tag == 902) {
        if (_secondList.count > 0) {
            return _secondList.count;
        }
        return 0;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView.tag == 901)  {
        NSString *cellStr;
        if (indexPath.row == 0) {
            cellStr = @"hotTypeCell1";
        } else if (indexPath.row == 1) {
            cellStr = @"hotTypeCell2";
        } else if (indexPath.row == 2) {
            cellStr = @"hotTypeCell3";
        }
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellStr forIndexPath:indexPath];
        
        return cell;
    } else {
        static NSString *cellStr = @"recomCell";
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellStr forIndexPath:indexPath];
//        UIView *containView = [cell viewWithTag:301];
        if (_secondList.count > 0) {
            // 商品图片
            NSString *goodImageUrl;
            if (indexPath.row < _secondList.count) {
                goodImageUrl = _secondList[indexPath.row][@"icon"];
            }
            UIImageView *goodImageView = (UIImageView *)[cell viewWithTag:101];
            if (![goodImageUrl isEqual:[NSNull null]]) {
                NSInteger width = goodImageView.width * 2;
                NSInteger height = goodImageView.height * 2;
                goodImageUrl = [NSString stringWithFormat:@"%@?dp_cmd=/imageView2/mode/2/w/%ld/h/%ld/",goodImageUrl,(long)width,(long)height];
                [goodImageView sd_setImageWithURL:[NSURL URLWithString:goodImageUrl] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            }
        } else {
            UIImageView *goodImageView = (UIImageView *)[cell viewWithTag:101];
            goodImageView.image = [UIImage imageNamed:@"placeholder"];
        }
        // 商品名称
        UILabel *goodNameLabel = (UILabel *)[cell viewWithTag:102];
        NSString *goodName;
        if (indexPath.row < _secondList.count) {
            goodName = _secondList[indexPath.row][@"name"];
        }
        if (![goodName isEqual:[NSNull null]]) {
            goodNameLabel.text = goodName;
        }
        // 商品折扣价格
        UILabel *goodDiscountLabel = (UILabel *)[cell viewWithTag:103];
        // 商品价格
        UILabel *goodPriceLabel = (UILabel *)[cell viewWithTag:104];
        NSString *goodDiscount;
        NSString *goodPrice;
        if (indexPath.row < _secondList.count) {
            goodDiscount = _secondList[indexPath.row][@"commodityPrice"][@"discount"];
            goodPrice = _secondList[indexPath.row][@"commodityPrice"][@"price"];
        }
        if (![goodDiscount isEqual:[NSNull null]] &&
            ![goodPrice isEqual:[NSNull null]]) {
            // 折扣价格
            CGFloat discount = [goodDiscount floatValue];
            CGFloat price = [goodPrice floatValue];
            goodDiscountLabel.text = [NSString stringWithFormat:@"¥ %.2f",price * discount];
            // 价格
            NSString *str = [NSString stringWithFormat:@"¥ %.2f",[goodPrice floatValue]];
            NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
            NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attribtDic];
            goodPriceLabel.attributedText = attribtStr;
            if (discount >= 1.0 || [goodPriceLabel.text isEqualToString:goodDiscountLabel.text]) {
                goodPriceLabel.hidden = YES;
            } else {
                goodPriceLabel.hidden = NO;
            }
        }
        UIView *line = [cell viewWithTag:105];
        for (NSLayoutConstraint* constraint in line.constraints) {
            if (constraint.firstAttribute == NSLayoutAttributeHeight) {
                constraint.constant = 0.5;
            }
        }
        line.height = 0.5;
        
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width,height;
    if (collectionView.tag == 901) {
        width = [UIScreen mainScreen].bounds.size.width;
        height = width * typeHeightWidthRatio;
        return (CGSize){width,height / 3};
    } else if (collectionView.tag == 902) {
        width = ([UIScreen mainScreen].bounds.size.width - 6.0 - 4.0) / 2;
        if (kScreen_Width <= 320.0) {
            _recomHeightWidthRatio = 1.362;
        } else if (kScreen_Width > 320.0 && kScreen_Width <= 375.0) {
            _recomHeightWidthRatio = 1.362;
        } else {
            _recomHeightWidthRatio = 1.362;
        }
        height = width * _recomHeightWidthRatio;
        return (CGSize){width,height};
    }
    return (CGSize){width,width};
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView.tag == 902) {
        if (_secondList.count > 0) {
            NSDictionary *goodDic = _secondList[indexPath.row];
            NSString *commodityId = goodDic[@"commodityId"];
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
            BDGoodDetailViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"goodDetailStoryboardID"];
            detailVC.commodityId = commodityId;
            //        detailVC.isFromHomePage = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    if (_firstList.count > 0) {
        NSString *commodityId = _firstList[index][@"commodityId"];
        if ([commodityId isEqual:[NSNull null]] ||
            commodityId != nil) {
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
            BDGoodDetailViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"goodDetailStoryboardID"];
            detailVC.commodityId = commodityId;
            detailVC.isFromHomePage = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

#pragma mark IBActions

- (IBAction)ganziTypeButtonPressed:(UIButton *)sender {
    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"ThirdStoryboard" bundle:[NSBundle mainBundle]];
    BDGanziTypeViewController *vc = [stroyboard instantiateViewControllerWithIdentifier:@"ganziTypeStoryboardID"];
    NSArray *firstArr = @[@"食品",@"服饰",@"药材",@"奢侈礼品",@"手工艺",@"其他"];
    NSArray *secondArr = @[@[@"菌类",@"肉类",@"保健品",@"冷冻生鲜",@"干货",@"特色饮品",@"其他"],
                           @[@"包类",@"鞋服",@"首饰",@"配件",@"户外",@"生活",@"其他"],
                           @[@"药材"],
                           @[@"非物质文化遗产",@"其他"],
                           @[@"手工艺"],
                           @[@"图书",@"生鲜",@"干货",@"其他"]];
    
    
    vc.firstArr = firstArr;
    vc.secondArr = secondArr;
    vc.storeType = @"MINMAO_CHAIN";
    [self.navigationController pushViewController:vc animated:YES];
}


- (IBAction)hotButtonPressed:(UIButton *)sender {// 701 - 705
    NSArray *list = @[@"食品",@"服饰",@"药材",@"手工艺",@"奢侈礼品"];
    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"ThirdStoryboard" bundle:[NSBundle mainBundle]];
    BDGanziSearchViewController *searchVC = [stroyboard instantiateViewControllerWithIdentifier:@"ganziSearchStoryboardID"];
    searchVC.storeType = @"MINMAO_CHAIN";
    searchVC.secondTitle = list[sender.tag - 701];
    searchVC.thridTitle = list[sender.tag - 701];
    if ([searchVC.secondTitle isEqualToString:@"奢侈礼品"]) {// 奢侈礼品是一级分类,所有级别上升一级
        searchVC.firstTitle = searchVC.secondTitle;
    }
    [self.navigationController pushViewController:searchVC animated:YES];
}

@end
